/***************************************
 * @update: 2021-05-26  LiLinBin  [创建文件]
 * @update: 2021-05-26  LiLinBin  [添加uuid]
 * 
 * @description: 数据处理工具
 ***************************************/

import { Modal } from 'ant-design-vue';


/**
* 生成UUID
* @returns {string}
*/
const uuid = function () {
	const S4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
	return (S4() + S4() + "" + S4() + "" + S4() + "" + S4() + "" + S4() + S4() + S4());
}




/**
 * @augments msNum [Number] 需要转换的毫秒, new Date(xx).getTime()
 * @augments symbol [String] 日期分割符号, 2021-09-01
 * @return 2021-09-01 16:00:00
 */
const convertTime = function (msNum, symbol) {
	if (!msNum) return
	symbol = symbol || '-'

	const t = new Date(msNum)
	const year = t.getFullYear()
	const month = (t.getMonth() + 1 + '').padStart(2, '0')
	const date = (t.getDate() + '').padStart(2, '0')
	const time = /\d{2}:\d{2}:\d{2}/.exec(t)

	return `${year}${symbol}${month}${symbol}${date} ${time}`
}



/**
* 拼接属性 (用于changeMixin改变属性配置项)
* @param attrObj [Object] 属性对象信息
* @return 拼接好的字符串 [String]
*/

// 需要增加单位的属性
const needUnits = [
	"border-bottom-width",
	"border-left-width",
	"border-right-width",
	"border-top-width",
	"bottom",
	"left",
	"right",
	"top",
	"font-size",
	"height",
	// "line-height",	//行高可以不带单位
	"max-height",
	"min-height",
	"width",
	"max-width",
	"min-width",
	"margin-bottom",
	"margin-left",
	"margin-right",
	"margin-top",
	"padding-bottom",
	"padding-left",
	"padding-right",
	"padding-top",
	"border-radius",
	"text-indent"
]
const joinAttr = function (attrObj) {
	let str = ''

	Object.keys(attrObj).forEach(key => {
		if (key === 'style') {
			const customStyle = attrObj[key].trim().replace(/\s+/g, ' ')
			//以分号";"为结束标识
			if (customStyle.lastIndexOf(";") !== customStyle.length - 1) return
			str += customStyle
			return
		}

		const myKey = key.replace(/([A-Z])/g, match => "-" + match.toLowerCase())
		let value = attrObj[key]

		if (value && myKey === 'font-color') {
			const pureFontColor = `color: ${value};`
			const gradientFontColor = `background-image: ${value};-webkit-background-clip:text;-webkit-text-fill-color:transparent;`

			str += value.includes("linear-gradient") ? gradientFontColor : pureFontColor
		}

		//渐变没有 url
		if (
			myKey === 'background-image' &&
			value &&
			!value.includes("linear-gradient")
		) {
			const val = value === 'inherit' ? 'inherit;' : `url(${value});`
			str += `${myKey}: ${val}`
			return
		}

		if (needUnits.indexOf(myKey) > -1) {
			// 是否需要单位
			const hasUnit = Number(value) != value
			!hasUnit && (value = value + 'px')
		}
		str += `${myKey}: ${value};`
	})

	return str
}




/**
* 添加日期格式化工具
* 例1: new Date().format('YYYY年M月d日 hh:m:s')
* 例2: new Date('2012-5-3').format('YYYY/MM/dd hh:mm:ss')
*/
const newDateFormat = function () {
	Date.prototype.format = function (format) {
		const date = {
			"M+": this.getMonth() + 1,
			"d+": this.getDate(),
			"h+": this.getHours(),
			"m+": this.getMinutes(),
			"s+": this.getSeconds(),
			"q+": Math.floor((this.getMonth() + 3) / 3),
			"S+": this.getMilliseconds()
		};

		if (/(y+)/i.test(format)) {
			format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
		}

		for (let k in date) {
			if (new RegExp("(" + k + ")").test(format)) {
				format = format.replace(RegExp.$1, RegExp.$1.length == 1
					? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
			}
		}
		return format;
	}
}




/**
 * 对接口数据进行过滤
 * @param {Object|Array} resData 
 * @param {String} dataFilterJs 
 */
const resDataFilter = function (resData, dataFilterJs) {
	if (!dataFilterJs) return resData

	try {
		const jsStr = "() => {" + dataFilterJs + "}"
		return eval(jsStr)()
	} catch (err) {
		console.error("数据过滤脚本错误", err);
		Modal.confirm({
			title: '错误: 具体查看控制台错误提示!!!',
			content: new Error(err) + "",
			centered: true,
			maskClosable: true,
			okText: '知道了'
		})
		return resData
	}
}



/**
 * 获取组件$el字体相对html字体的倍数
 * @param {*} 
 * @return {number} 倍数
 * 用法: T.getFontRate.call(this)
 */
function getFontRate () {
	const elFs = window.getComputedStyle(this.$el.parentElement).getPropertyValue("font-size")

	const htmlFs = window.getComputedStyle(document.body).getPropertyValue("font-size")

	const times = parseFloat(elFs) / parseFloat(htmlFs)

	return times
}




/**
 * 将px单位换成em，
 * @param {*} 需要转换的px数值
 * @return {number} 带em单位的值
 * 用法: T.pxToEm(36)
 */
function pxToEm (pxValue) {
	const value = Number(pxValue);
	if (isNaN(value)) {
		console.warn('pxToEm方法需要传入数值！');
		return
	}
	const htmlFs = window.getComputedStyle(document.body).getPropertyValue("font-size")
	const emValue = pxValue / parseFloat(htmlFs);
	const newEmValue = Math.ceil(emValue * 100) / 100;
	return `${newEmValue}em`
}




/**
 * 设置行高，将行高转换成em单位
 * @param {*} lineHeight：行高， fontSize：当前元素字体大小
 * @return {number} 带em单位的行高
 * 用法: T.setLineHeight(36, 36)
 */
function setLineHeight (lineHeight, fontSize) {
	const lineHeightEm = parseFloat(pxToEm(lineHeight));
	const fontSizeEm = parseFloat(pxToEm(fontSize));
	const emValue = lineHeightEm / fontSizeEm
	const newEmValue = Math.ceil(emValue * 100) / 100;
	return `${newEmValue}em`
}





export {
	uuid,
	convertTime,
	joinAttr,
	newDateFormat,
	resDataFilter,
	getFontRate,
	pxToEm,
	setLineHeight
}